#!/bin/bash

# 确保脚本以root用户运行
if [ "$(id -u)" -ne 0 ]; then
    echo "请使用root用户运行此脚本" >&2
    exit 1
fi

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# 显示脚本开始信息
echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}     CentOS 8 Docker 安装脚本           ${NC}"
echo -e "${GREEN}=========================================${NC}"

# 检查系统版本
if [ -f /etc/os-release ]; then
    . /etc/os-release
    if [ "$ID" != "centos" ] || [ "$VERSION_ID" != "8" ]; then
        echo -e "${RED}错误: 此脚本仅适用于 CentOS 8${NC}" >&2
        exit 1
    fi
else
    echo -e "${RED}错误: 无法确定操作系统版本${NC}" >&2
    exit 1
fi

# 新增：禁用防火墙
echo -e "${YELLOW}禁用防火墙...${NC}"
systemctl stop firewalld
if [ $? -ne 0 ]; then
    echo -e "${RED}警告: 停止防火墙失败，可能需要手动设置${NC}" >&2
else
    echo -e "${GREEN}防火墙已停止${NC}"
fi

systemctl disable firewalld
if [ $? -ne 0 ]; then
    echo -e "${RED}警告: 禁用防火墙失败，可能需要手动设置${NC}" >&2
else
    echo -e "${GREEN}防火墙已禁用${NC}"
fi

# 新增：禁用SELinux
echo -e "${YELLOW}禁用SELinux...${NC}"
setenforce 0
if [ $? -ne 0 ]; then
    echo -e "${RED}警告: 临时禁用SELinux失败，可能需要手动设置${NC}" >&2
else
    echo -e "${GREEN}SELinux已临时禁用${NC}"
fi

sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
if [ $? -ne 0 ]; then
    echo -e "${RED}警告: 永久禁用SELinux失败，可能需要手动设置${NC}" >&2
else
    echo -e "${GREEN}SELinux已设置为永久禁用（需要重启生效）${NC}"
fi

# 新增：配置阿里云镜像源
echo -e "${YELLOW}配置阿里云镜像源...${NC}"
# 备份原始repo文件
mkdir -p /etc/yum.repos.d/bak
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak/ 2>/dev/null

# 创建阿里云BaseOS源
cat > /etc/yum.repos.d/CentOS-Base.repo << EOF
[BaseOS]
name=CentOS-\$releasever - Base
baseurl=https://mirrors.aliyun.com/centos/\$releasever/BaseOS/\$basearch/os/
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-Official

[AppStream]
name=CentOS-\$releasever - AppStream
baseurl=https://mirrors.aliyun.com/centos/\$releasever/AppStream/\$basearch/os/
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/centos/RPM-GPG-KEY-CentOS-Official
EOF

# 配置阿里云epel源
cat > /etc/yum.repos.d/epel.repo << EOF
[epel]
name=Extra Packages for Enterprise Linux 8 - \$basearch
baseurl=https://mirrors.aliyun.com/epel/8/Everything/\$basearch
enabled=1
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-8
EOF

# 清理并生成缓存
dnf clean all
dnf makecache
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: 阿里云镜像源配置失败${NC}" >&2
    exit 1
fi
echo -e "${GREEN}阿里云镜像源配置完成${NC}"

# 新增：检查并停止运行中的Docker服务
echo -e "${YELLOW}检查Docker服务状态...${NC}"
if systemctl is-active --quiet docker; then
    echo -e "${YELLOW}Docker服务正在运行，正在停止...${NC}"
    systemctl stop docker
    if [ $? -ne 0 ]; then
        echo -e "${RED}错误: 停止Docker服务失败${NC}" >&2
        exit 1
    fi
    echo -e "${GREEN}Docker服务已成功停止${NC}"
else
    echo -e "${GREEN}Docker服务未运行${NC}"
fi

# 新增：检查并卸载已安装的Docker
echo -e "${YELLOW}检查并卸载已安装的Docker...${NC}"
if rpm -q docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine >/dev/null 2>&1; then
    echo -e "${YELLOW}发现已安装的Docker，正在卸载...${NC}"
    dnf remove -y docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine
    if [ $? -ne 0 ]; then
        echo -e "${RED}错误: 卸载已安装的Docker失败${NC}" >&2
        exit 1
    fi
    echo -e "${GREEN}已成功卸载旧版本Docker${NC}"
else
    echo -e "${GREEN}未发现已安装的Docker${NC}"
fi

# 步骤3: 设置Docker存储库
echo -e "${YELLOW}步骤 3: 设置Docker存储库...${NC}"
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: Docker存储库设置失败${NC}" >&2
    exit 1
fi
echo -e "${GREEN}Docker存储库设置完成${NC}"

# 步骤4: 安装Docker引擎
echo -e "${YELLOW}步骤 4: 安装Docker引擎...${NC}"
dnf install -y docker-ce docker-ce-cli containerd.io
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: Docker引擎安装失败${NC}" >&2
    exit 1
fi
echo -e "${GREEN}Docker引擎安装完成${NC}"

# 步骤5: 启动并启用Docker服务
echo -e "${YELLOW}步骤 5: 启动并启用Docker服务...${NC}"
systemctl start docker
systemctl enable docker
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: Docker服务启动或启用失败${NC}" >&2
    exit 1
fi
echo -e "${GREEN}Docker服务已启动并设置为开机自启${NC}"

# 新增：配置Docker镜像加速和远程访问
echo -e "${YELLOW}配置Docker镜像加速和远程访问...${NC}"
echo '{"registry-mirrors":["https://docker.1ms.run"]}' | sudo tee /etc/docker/daemon.json > /dev/null
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: Docker配置文件创建失败${NC}" >&2
    exit 1
fi

# 重启Docker服务使配置生效
echo -e "${YELLOW}重启Docker服务使配置生效...${NC}"
systemctl restart docker
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: Docker服务重启失败${NC}" >&2
    exit 1
fi
echo -e "${GREEN}Docker配置完成${NC}"

# 步骤6: 验证Docker安装
echo -e "${YELLOW}步骤 6: 验证Docker安装...${NC}"
docker run --rm hello-world
if [ $? -ne 0 ]; then
    echo -e "${RED}错误: Docker验证失败，请检查安装${NC}" >&2
    exit 1
fi
echo -e "${GREEN}Docker安装验证成功${NC}"

# 步骤7: 添加当前用户到docker组（可选）
echo -e "${YELLOW}步骤 7: 添加当前用户到docker组（可选）...${NC}"
read -p "是否将当前用户添加到docker组？(y/n): " answer
if [ "$answer" == "y" ]; then
    current_user=$(logname)
    usermod -aG docker $current_user
    if [ $? -ne 0 ]; then
        echo -e "${RED}错误: 添加用户到docker组失败${NC}" >&2
    else
        echo -e "${GREEN}用户 $current_user 已添加到docker组${NC}"
        echo -e "${YELLOW}注意: 您需要注销并重新登录才能使此更改生效${NC}"
    fi
else
    echo -e "${YELLOW}跳过添加用户到docker组${NC}"
fi

# 显示安装完成信息
echo -e "${GREEN}=========================================${NC}"
echo -e "${GREEN}    Docker 已成功安装在您的系统上!     ${NC}"
echo -e "${GREEN}=========================================${NC}"
echo -e "${YELLOW}您现在可以使用docker命令来管理容器${NC}"    